<template>

  <div class="app-container">
    <div class="filter-container">
      <el-button
        class="filter-item"
        type="primary"
        v-if="~accessable.indexOf('marketing_activity:add'+marketingType)"
        v-waves
        icon="el-icon-plus"
        @click="handleUpdate(null)"
      >添加</el-button>
      <el-button
        class="filter-item"
        type="primary"
        v-if="~accessable.indexOf('marketing_activity:export'+marketingType)"
        v-waves
        icon="el-icon-document"
        @click="exportExcelFile"
      >导出</el-button>
    </div>
    <el-table
      :data="list"
      :height="tableHeight"
      @sort-change="sortChange"
      v-loading="listLoading"
      element-loading-text="给我一点时间"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <!-- <el-table-column align="center" type="index" label="序号" width="80">
      </el-table-column>-->
      <el-table-column width="200" prop="activityName" align="center" label="活动名称"></el-table-column>

      <el-table-column prop="startDate" align="center" label="开始日期" width="160">
        <template slot-scope="scope">
          <span>{{scope.row.startDate|parseTime}}</span>
        </template>
      </el-table-column>

      <el-table-column prop="endDate" align="center" label="截止时间" width="160">
        <template slot-scope="scope">
          <span>{{scope.row.endDate|parseTime}}</span>
        </template>
      </el-table-column>

      <el-table-column prop="_" align="center" label="二维码" width="160">
        <template slot-scope="scope">
          <a @click="showQrcode(scope.row)" style="color:blue;" href="javascript:void(0)">查看</a>
        </template>
      </el-table-column>

      <el-table-column prop="checkStatus" align="center" label="审核状态" width="120">
        <template slot-scope="scope">
          <el-tag :type="scope.row.checkStatus | checkstatustagFilter">{{scope.row.checkStatus|checkStatusFilter}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="checkRemark" align="center" label="审核意见" width="180"></el-table-column>

      <el-table-column prop="status" align="center" label="状态" width="160">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status | statustagFilter">{{scope.row.status|statusFilter}}</el-tag>
        </template>
      </el-table-column>

      <!--

      <el-table-column prop="imgSrc" align="center" label="图片" width="150">
        <template slot-scope="scope">
          <img :src="scope.row.imgSrc|absUrl" alt="" class="img-src">
        </template>
      </el-table-column>-->
      <el-table-column align="center" label="操作" width="480" class-name="small-padding" fixed="right">
        <template slot-scope="scope">
          <el-button type="primary" v-if="~accessable.indexOf('marketing_activity:resolve'+marketingType) && scope.row.status==0" size="mini" @click="doPass(scope.row)">审核通过</el-button>
          <el-button type="danger" v-if="~accessable.indexOf('marketing_activity:reject'+marketingType) && scope.row.status==0" size="mini" @click="doReject(scope.row)">审核拒绝</el-button>
          <el-button type="primary" v-if="~accessable.indexOf('marketing_activity:edit'+marketingType)" size="mini" @click="editRow(scope.row)">修改</el-button>
          <!-- <el-button type="primary" v-if="scope.row.status==1" size="mini" @click="stop(scope.row)">停止</el-button>
          <el-button type="primary" v-if="scope.row.status==0" size="mini" @click="start(scope.row)">启动</el-button>-->
          <el-button size="mini" v-if="~accessable.indexOf('marketing_activity:delete'+marketingType)" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          <el-button size="mini" v-if="~accessable.indexOf('marketing_activity:prizelist'+marketingType)" type="success" @click="seePrize(scope.row)">查看中奖信息</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="params.pageNo"
        :page-sizes="[10,20,30,50]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <el-dialog :title="isEditing?'修改':'添加'" :visible.sync="dialogFormVisible" width="1100px">
      <el-form
        class="dialog-form"
        :rules="rules"
        ref="dataForm"
        :model="temp"
        label-position="left"
        label-width="120px"
      >
        <el-form-item label="活动名称" prop="activityName">
          <el-input v-model="temp.activityName" maxlength="100" placeholder="活动名称"></el-input>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startDate">
              <el-date-picker
                v-model="temp.startDate"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetime"
                placeholder="选择时间"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="截止时间" prop="endDate">
              <el-date-picker
                value-format="yyyy-MM-dd HH:mm:ss"
                v-model="temp.endDate"
                type="datetime"
                placeholder="选择日期"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="可抽奖次数" prop="playNum">
              <el-input-number v-model="temp.playNum" placeholder="可抽奖次数"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="temp.status">
                <el-radio
                  v-for="(item,value) in statusFilter"
                  :key="value"
                  :label="value"
                  :value="value"
                >{{item}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="活动简介" prop="intro">
          <div class="quill-wrap" style="height:500px;">
            <quill-editor style="height:400px;" v-model="temp.intro" ref="myQuillEditor" :options="editorOption">
            </quill-editor>
          </div>
        </el-form-item>
        <el-form-item label="奖品信息" prop="prizeList">
                <div class="clearfix">
            <div class="lcontent">
              <el-row :gutter="10">
                <el-col :span="4">
                  奖品等级
                </el-col>
                <el-col :span="5">
                  奖品名称
                </el-col>
                <el-col :span="5">
                  奖品描述
                </el-col>
                <el-col :span="5">
                  奖品数量
                </el-col>
                <el-col :span="5">
                  奖品概率
                </el-col>
              </el-row>
            </div>
          </div>
          <div
            class="clearfix"
            v-for="(detail,idx) in temp.prizeList"
            :key="idx"
          >
            <div class="lcontent">
              <el-row :gutter="10">
                <el-col :span="4">
                    <el-select v-model="detail.prizeLevel" placeholder="奖品等级">
                    <el-option v-for="p in prizeLevels" :label="p.title" :value="p.value" :key="p.value"></el-option>
                  </el-select>
                </el-col>
                <el-col :span="5">
                  <el-input v-model="detail.prizeName" placeholder="奖品名称"/>
                </el-col>
                <el-col :span="5">
                  <el-input v-model="detail.prizeDesc" placeholder="奖品描述"/>
                </el-col>
                <el-col :span="5">
                  <el-input v-model="detail.prizeNum" placeholder="奖品数量"/>
                </el-col>
                <el-col :span="5">
                  <el-input v-model="detail.prizeRate" placeholder="奖品概率"/>
                </el-col>
              </el-row>
            </div>
            <div class="fr">
              <el-button
                type="danger"
                @click="deletePrize(detail,idx)"
                size="mini"
              >删除</el-button>
            </div>
          </div>
          <div class="clearfix">
            <el-button type="primary" @click="addPrize" size="mini">添加奖品</el-button>
          </div>
        </el-form-item>
        <!-- <el-form-item label="图片" prop="imgSrc">
          <el-upload class="avatar-uploader" :action="UPLOAD_URL" :show-file-list="false" :on-success="handleAvatarSuccess('imgSrc')"
            :before-upload="beforeAvatarUpload">
            <img v-if="temp.imgSrc" :src="temp.imgSrc|absUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" :loading="submiting" @click="submitFormAction">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="查看二维码" :visible.sync="qrcodeDataDialogShowed" width="400px">
        <div class="text-center">
            <img :src="qrcodeData" alt="" style="width:300px;">
        </div>
    </el-dialog>
    <el-dialog title="中奖信息" :visible.sync="prizeLogListDialogShowed" width="1050px">
        <div class="filter-container">
        <el-date-picker clearable :editable="false" size="small" style="width:140px" v-model="searchPrizeCondition.startDate" placeholder="开始日期" value-format="yyyy-MM-dd"></el-date-picker>
        <el-date-picker clearable :editable="false" size="small" style="width:140px" v-model="searchPrizeCondition.endDate" placeholder="截止时间" value-format="yyyy-MM-dd"></el-date-picker>
        <el-input clearable style="width:180px"  @keyup.enter.native="doSearchPrizeLog" size="small" placeholder="手机号码" v-model="searchPrizeCondition.mobile"></el-input>
        <el-select clearable v-model="searchPrizeCondition.prizeLevel" size="small" placeholder="奖品等级" style="width:140px">
            <el-option v-for="p in prizeLevels" :label="p.title" :value="p.value" :key="p.value"></el-option>
        </el-select>
      <el-button
        class="filter-item"
        type="primary"
        v-waves
        size="small"
        icon="el-icon-search"
        @click="doSearchPrizeLog"
      >搜索</el-button>
      <el-button
        class="filter-item"
        size="small"
        type="primary"
        v-waves
        icon="el-icon-document"
        @click="exportPrizeLogExcelFile"
      >导出</el-button>
    </div>
        <el-table
        :data="prizeLogList"
        element-loading-text="给我一点时间"
        border
        fit
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column width="200" prop="activityDate" align="center" label="中奖日期">
          <template slot-scope="scope">
            <span>{{scope.row.activityDate|parseTime('{y}-{m}-{d}')}}</span>
          </template>
        </el-table-column>
        <el-table-column width="120" prop="mobile" align="center" label="用户手机"></el-table-column>
        <el-table-column width="140" prop="virtualcard" align="center" label="会员卡号"></el-table-column>
        <el-table-column width="140" prop="prizeLevel" align="center" label="奖品等级">
          <template slot-scope="scope">
            <span>{{scope.row.prizeLevel|prizeLevelFilter}}</span>
          </template>
        </el-table-column>
        <el-table-column width="200" prop="prizeName" align="center" label="奖品名称"></el-table-column>
        <el-table-column width="140" prop="prizeNum" align="center" label="中奖奖品数量"></el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handlePrizeLogSizeChange"
        @current-change="handlePrizeLogCurrentChange"
        :current-page.sync="searchPrizeCondition.pageNo"
        :page-sizes="[10,20,30,50]"
        :page-size="searchPrizeCondition.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="prizeLogTotal"
      ></el-pagination>
    </div>
    </el-dialog>
  </div>
</template>
<style scoped>
.avatar-uploader {
  width: 375px;
  height: 155px;
}

.avatar-uploader >>> .avatar {
  width: 375px;
  height: 155px;
}

.avatar-uploader >>> .avatar-uploader-icon {
  width: 375px;
  height: 155px;
}
.img-src {
  width: 100px;
}
.lcontent {
  margin-right: 90px;
  width: 88%;
  float: left;
}
.clearfix {
  position: relative;
  margin-bottom: 10px;
}
.clearfix::after {
  content: " ";
  display: table;
  height: 0;
  width: 0;
  clear: both;
}
.fr {
  position: absolute;
  right: 0;
  top: 0;
}
</style>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor, Quill } from 'vue-quill-editor'
import { container, ImageExtend, QuillWatch } from 'quill-image-extend-module'
import { parseTime } from '../filters'
Quill.register('modules/ImageExtend', ImageExtend)
let statusFilter = ['下线', '上线']
let statustagFilter = ['danger', 'success', 'info', 'warning']

let adPositionFilter = ['首页底部', '首页顶部', '特价专区', '限时抢购']
let adPositiontagFilter = ['success', 'danger', 'info', 'warning']
const Qrcode = require('qrcode')

export default {
  data () {
    const validateOrderSupplementDetails = (rule, value, callback) => {
      if (value && value.length) {
        value.every(el => {
          // goodsNo,goodsName,salePrice,saleCount
          if (!el.prizeLevel) {
            callback(new Error('奖品等级不能为空'))
            return false
          }
          if (!el.prizeName || !el.prizeName.trim()) {
            callback(new Error('奖品名称不能为空'))
            return false
          }
          if (!el.prizeDesc || !el.prizeDesc.toString().trim()) {
            callback(new Error('奖品描述不能为空'))
            return false
          }
          if (isNaN(el.prizeNum)) {
            callback(new Error('奖品数量必须为整数'))
            return false
          }
          if (isNaN(el.prizeRate) || (el.prizeRate < 0 || el.prizeRate > 10000000)) {
            callback(new Error('奖品概率必须是0~10000000之间的整数或小数(小数点后两位)'))
            return false
          }
          return true
        })
        callback()
      } else {
        callback()
      }
    }
    const validateStartEndDate = (rule, value, callback) => {
      if(!this.isEditing){
          if (this.temp.startDate && this.temp.startDate < parseTime(new Date())) {
            callback(new Error('开始时间不能小于当前时间'))
            return
          }
          if (this.temp.endDate && this.temp.endDate < parseTime(new Date())) {
            callback(new Error('结束时间不能小于当前时间'))
            return
          }
          if (this.temp.startDate && this.temp.endDate) {
            if (this.temp.startDate > this.temp.endDate) {
              callback(new Error('开始时间不能大于结束时间'))
              return
            }
        }
      }
      callback()
    }
    return {
      prizeLogList: [],
      tableHeight: 400,
      prizeLogListDialogShowed: false,
      qrcodeDataDialogShowed: false,
      total: 0,
      searchPrizeCondition: {
        pageNo: 1,
        pageSize: 10
      },
      prizeLevels: [
        {value: 1, title: '一等奖'},
        {value: 2, title: '二等奖'},
        {value: 3, title: '三等奖'},
        {value: 4, title: '四等奖'},
        {value: 5, title: '五等奖'},
        {value: 6, title: '六等奖'}
      ],
      qrcodeData: '',
      temp: {
        id: '',
        intro: '',
        activityName: '',
        startDate: '',
        playNum: 0,
        endDate: '',
        status: '',
        prizeList: []
      },
      editorOption: {
        placeholder: '在这里输入内容!',
        modules: {
          ImageExtend: {
            loading: true,
            name: 'file',
            action: '/util/upload',
            response: res => {
              return (
                'http://weixin-ostorage01.oss-cn-shenzhen.aliyuncs.com' +
                res.info
              )
            }
          },
          toolbar: {
            container: container,
            handlers: {
              image: function () {
                QuillWatch.emit(this.quill.id)
              }
            }
          }
        }
      },
      prizeLogTotal: 0,
      pickerOptions1: {
        shortcuts: [
          {
            text: '今天',
            onClick (picker) {
              picker.$emit('pick', new Date())
            }
          },
          {
            text: '昨天',
            onClick (picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          },
          {
            text: '一周前',
            onClick (picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', date)
            }
          }
        ]
      },
      statusFilter: statusFilter,
      params: {marketingType: this.marketingType, pageNo: 1, pageSize: 10},
      cityIdOptions: [],

      adPositionFilter: adPositionFilter,

      rules: {
        activityName: [
          {
            required: true,
            message: '活动名称不能为空',
            trigger: 'change'
          },
          {
            max: 50,
            message: '活动名称不能大于100个字',
            trigger: 'change'
          }
        ],
        playNum: [{
          required: true,
          message: '可抽奖次数不能为空'
        }],
        prizeList: [
          {
            required: true,
            message: '奖品信息不能为空',
            trigger: 'change',
            type: 'array'
          },
          {
            validator: validateOrderSupplementDetails,
            trigger: 'blur'
          }
        ],

        startDate: [
          {
            required: true,
            message: '开始日期不能为空',
            trigger: 'change'
          },
          {
            validator: validateStartEndDate,
            trigger: 'blur'
          }
        ],

        endDate: [
          {
            required: true,
            message: '结束日期不能为空',
            trigger: 'change'
          },
          {
            validator: validateStartEndDate,
            trigger: 'blur'
          }
        ],
        intro: [
          {
            required: true,
            message: '活动简介不能为空',
            trigger: 'change'
          }
        ],

        status: [
          {
            required: true,
            message: '请选择状态',
            trigger: 'change'
          }
        ]
      }
    }
  },
  components: {
    quillEditor
  },
  props: {
    marketingType: {
      type: Number,
      default: 1
    },
    title: {
      type: String
    }
  },
  created () {
    // this.init('ad', 1).loadData()
    this.loadData()

    // this.combOptions("city").then(info => {
    //   this.cityIdOptions = info;
    // });
    this.tableHeight = window.innerHeight - 300
  },
  filters: {
    prizeLevelFilter (level) {
      return {'1': '一等级', '2': '二等级', '3': '三等级', '4': '四等级', '5': '五等级', '6': '六等级'}[level]
    },
    checkStatusFilter (status) {
      return {0: '待审核', 5: '审核通过', 10: '审核拒绝'}[status]
    },
    checkstatustagFilter (status) {
      return {0: 'default', 5: 'success', 10: 'danger'}[status]
    },
    statusFilter (status) {
      return statusFilter[parseInt(status)]
    },
    statustagFilter (status) {
      return statustagFilter[parseInt(status)]
    },

    adPositionFilter (status) {
      return adPositionFilter[parseInt(status)]
    },
    adPositiontagFilter (status) {
      return adPositiontagFilter[parseInt(status)]
    }
  },
  methods: {
    handleCurrentChange () {
      this.loadData()
    },
    doPass (row) {
      this.$prompt('审核备注', '确认审核通过吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        this.$post('/admin/marketing_activity/check', {id: row.id, checkFlag: 1, checkRemark: value}).then(data => {
          this.$$notify('审核通过成功')
          this.loadData()
        })
      }).catch(() => {

      })
    },
    doReject (row) {
      this.$prompt('审核备注', '确认审核拒绝吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        this.$post('/admin/marketing_activity/check', {id: row.id, checkFlag: 0, checkRemark: value}).then(data => {
          this.$$notify('审核拒绝成功')
          this.loadData()
        })
      }).catch(() => {

      })
    },
    handlePrizeLogSizeChange (size) {
      this.searchPrizeCondition.pageSize = size
      this.doSearchPrizeLog()
    },
    handlePrizeLogCurrentChange (page) {
      this.searchPrizeCondition.pageNo = page
      this.doSearchPrizeLog()
    },
    showPrizeLogList (activityId) {
      this.searchPrizeCondition.activityId = activityId
      this.doSearchPrizeLog()
    },
    handleDelete (row) {
      this.$confirm('确认要删除吗？', '提醒', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$post('/admin/marketing_activity/delete', {id: row.id})
          .then(res => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.loadData()
          })
          .catch((info) => {

          })
      })
    },
    doSearchPrizeLog () {
      this.$post('/admin/marketing_activity/prize_log/list', this.searchPrizeCondition).then(data => {
        this.prizeLogTotal = data.total
        this.prizeLogList = data.rows || []
        console.log(this.prizeLogList)
      })
    },
    seePrize (row) {
      this.prizeLogListDialogShowed = true
      this.showPrizeLogList(row.id)
    },
    showQrcode (row) {
      this.qrcodeDataDialogShowed = true
      const url = ['zp', 'index', 'zjd'][this.marketingType - 1]
      // marketingType
      const link = process.env.h5Domain + '/h5/scratch-draw/' + url + '.html?id=' + row.id
      Qrcode.toDataURL(link, (err, url) => {
        if (!err) {
          this.qrcodeData = url
        }
      })
    },
    deletePrize (row, idx) {
      this.$$comfirm('确认删除该奖品吗?', () => {
        this.temp.prizeList.splice(idx, 1)
      })
    },
    editRow (row) {
      this.queryDetail(row.id, data => {
        data.startDate = parseTime(data.startDate)
        data.endDate = parseTime(data.endDate)
        this.temp = data
        this.isEditing = true
        this.dialogFormVisible = true
      })
    },
    queryDetail (id, callback) {
      this.$post('/admin/marketing_activity/detail', {id}).then(data => {
        callback && callback(data)
      })
    },
    submitFormAction () {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.submiting = true
          const postData = Object.assign({}, this.temp)
          postData.prizeList.forEach((el, idx) => {
            Object.keys(el).forEach(k => {
              postData['prizeList[' + idx + '].' + k] = el[k]
            })
          })
          if (!postData.id) {
            delete postData.id
          }
          delete postData.prizeList
          postData.marketingType = this.marketingType
          let url = '/admin/marketing_activity/add'
          if (this.isEditing) {
            url = '/admin/marketing_activity/modify'
          }
          this.$post(url, postData)
            .then(data => {
              this.loadData()
              this.$$notify('操作成功')
              this.dialogFormVisible = false
            })
            .finally(_ => {
              this.submiting = false
            })
        }
      })
    },
    deleteOrderSupplementDetail (detail, idx) {
      const id = detail.id
      if (!id) {
        this.temp.prizeList.splice(idx, 1)
      } else {
        let cIdx = 0
        this.temp.prizeList.forEach((el, idx) => {
          if (el.id === detail.id) {
            cIdx = idx
          }
        })
        detail.deleted = true
        this.$set(this.temp.prizeList, cIdx, detail)
      }
    },
    addPrize () {
      this.temp.prizeList.push({})
    },
    loadData () {
      this.$post('/admin/marketing_activity/list', this.params).then(
        data => {
          this.list = data.rows
          this.total = data.total
        }
      )
    },
    exportPrizeLogExcelFile () {
      this.$post('/admin/marketing_activity/prize_log/export', {...this.searchPrizeCondition,
        title: '中奖信息',
        fields: JSON.stringify([
          {
            field: 'activityDate',
            title: '中奖日期'
          },
          {
            field: 'prizeLevel',
            title: '奖品等级',
            valueMap: {'1': '一等级', '2': '二等级', '3': '三等级', '4': '四等级', '5': '五等级', '6': '六等级'}
          },

          {
            field: 'mobile',
            title: '用户手机'
          },
          {
            field: 'virtualcard',
            title: '会员卡号'
          },
          {
            field: 'prizeName',
            title: '奖品名称'
          },
          {
            field: 'prizeNum',
            title: '中奖奖品数量'
          }
        ])
      }).then(info => {
        this.openWin(info)
      })
    },
    exportExcelFile () {
      this.$post('/admin/marketing_activity/export', {...this.params,
        title: this.title + '活动列表',
        fields: JSON.stringify([
          {
            field: 'activityName',
            title: '活动名称'
          },
          {
            field: 'startDate',
            title: '开始日期'
          },
          {
            field: 'endDate',
            title: '截止时间'
          },
          {
            field: 'checkStatus',
            title: '审核状态',
            valueMap: {0: '待审核', 5: '审核通过', 10: '审核拒绝'}
          },
          {
            field: 'status',
            title: '状态',
            valueMap: ['下线', '上线']
          }
        ])
      }).then(info => {
        this.openWin(info)
      })
    }
  }
}
</script>
